from .xt_future_utils import http_get_request, api_key_get, api_key_post


class XT:
    
    def __init__(self, url, access_key, secret_key):
        self.__url = url
        self.__access_key = access_key
        self.__secret_key = secret_key

    def get_market_config(self, symbol):
        """
        symbol:
        :return:获取单个交易对的配置信息
        """
        params = {"symbol": symbol}
        url = self.__url + "/future/market" + '/v1/public/symbol/detail'
        return http_get_request(url, params=params)

    def get_all_pair_info(self):
        """
        :return:获取交易对币种
        """
        url = self.__url + "/future/market" + '/v1/public/symbol/coins'
        return http_get_request(url, params="")

    def get_funding_rate(self, symbol):
        """
        :return:获取资金费率
        """
        params = {"symbol": symbol}
        url = self.__url + "/future/market" + '/v1/public/q/funding-rate'
        return http_get_request(url, params=params)

    def get_agg_tiker(self, symbol):
        """
        :return:返回聚合行情
        """
        params = {"symbol": symbol}
        url = self.__url + "/future/market" + '/v1/public/q/agg-ticker'
        return http_get_request(url, params=params)

    def get_last_price(self, symbol, length):
        """
        :return:获取最近成交记录
        """
        params = {"symbol": symbol, "num": length}
        url = self.__url + "/future/market" + '/v1/public/q/deal'
        return http_get_request(url, params=params)

    def get_depth(self, symbol, depth):
        """
        :return:获取深度数据
        """
        params = {"symbol": symbol, "level": depth}
        url = self.__url + "/future/market" + '/v1/public/q/depth'
        return http_get_request(url, params=params)

    def get_account_capital(self):
        """
        :return:获取账户资金
        """
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/balance/list'
        url = self.__url + path
        return api_key_get(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                           bodymod=bodymod, params={})

    def get_coin_balance(self, coin):
        """
        :return:获取账户资金
        """
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/balance/detail'
        params = {"coin": coin}
        url = self.__url + path
        return api_key_get(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                           bodymod=bodymod, params=params)

    def get_history_order(self):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/trade" + '/v1/order/list-history'
        url = self.__url + path
        return api_key_get(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                           bodymod=bodymod, params={})

    def get_account_order(self, symbol, state, page, size):
        """
        state:
        订单状态 NEW：新建订单（未成交）；
        PARTIALLY_FILLED：部分成交；
        FILLED：全部成交；CANCELED：用户撤销；
        REJECTED：下单失败；EXPIRED：已过期；
        UNFINISHED：未完成；HISTORY：（历史）
        """
        bodymod = "application/x-www-form-urlencoded"
        # path = "/future/trade" + '/v1/order-entrust/list'
        path = '/future/trade/v1/order/list'
        url = self.__url + path
        params = {
            "symbol": symbol,
            "state": state,
            "page": page,
            "size": size
        }
        return api_key_get(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                           bodymod=bodymod, params=params)

    def get_position(self, symbol):
        """
        获取持仓信息
        :return:
        """
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/position/list'
        url = self.__url + path
        params = {
            "symbol": symbol,
        }
        return api_key_get(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                           bodymod=bodymod, params=params)

    def get_index_price(self, symbol, size):
        """
        :return:获取深度数据
        """
        params = {"symbol": symbol, "size": size}
        # url = self.__url + "/future/market" + '/v1/public/q/symbol-mark-price'
        url = self.__url + "/future/market" + '/v1/public/q/symbol-index-price'
        return http_get_request(url, params=params)

    def get_mark_price(self, symbol, size):
        """
        :return:获取深度数据
        """
        params = {"symbol": symbol, "size": size}
        url = self.__url + "/future/market" + '/v1/public/q/symbol-mark-price'
        # url = self.__url + "/future/market" + '/v1/public/q/symbol-index-price'
        return http_get_request(url, params=params)

    def get_order_id(self, order_id):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/api" + '/v1/order/detail'
        url = self.__url + path
        params = {
            "orderId": order_id
        }
        return api_key_get(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                           bodymod=bodymod, params=params)

    def get_batch_order_id(self, order_id_list: list):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/trade" + '/v1/order/list-by-ids'
        url = self.__url + path
        order_id_query = ",".join(order_id_list)
        params = {
            "ids": order_id_query
        }
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def send_order(self, symbol, price, amount, order_side, order_type, position_side, timeInForce='GTC'):
        """
        :return:获取账户资金
        """
        params = {"orderSide": order_side,
                  "orderType": order_type,
                  "origQty": amount,
                  "positionSide": position_side,
                  "symbol": symbol,
                  "price": price,
                  'timeInForce': timeInForce}

        bodymod = "application/x-www-form-urlencoded"
        path = "/future/trade" + '/v1/order/create'
        url = self.__url + path
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def send_batch_order(self, order_list: list):
        """
        :return:获取账户资金
        """
        params = {"list": str(order_list)}

        bodymod = "x-www-form-urlencoded"
        path = "/future/trade" + '/v1/order/create-batch'
        url = self.__url + path
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def cancel_order(self, order_id):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/trade" + '/v1/order/cancel'
        url = self.__url + path
        params = {
            "orderId": order_id
        }
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def cancel_all_order(self):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/trade" + '/v1/order-entrust/cancel-all'
        url = self.__url + path
        params = {}
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def set_account_leverage(self, leverage, position_side, symbol):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/position/adjust-leverage'
        url = self.__url + path
        params = {
            "leverage": leverage,
            "positionSide": position_side,
            "symbol": symbol
        }
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def set_merge_position(self, symbol):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/position/merge'
        url = self.__url + path
        params = {
            "symbol": symbol
        }
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def set_auto_margin(self, symbol, position_side):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/position/auto-margin'
        url = self.__url + path
        params = {
            "symbol": symbol,
            'positionSide': position_side,
            'autoMargin': 'false'
        }
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def close_all_position(self):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/position/close-all'
        url = self.__url + path
        params = {}
        return api_key_post(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                            bodymod=bodymod, params=params)

    def get_listen_key(self):
        bodymod = "application/x-www-form-urlencoded"
        path = "/future/user" + '/v1/user/listen-key'
        url = self.__url + path
        params = {}
        return api_key_get(path=path, url=url, access_key=self.__access_key, secret_key=self.__secret_key,
                           bodymod=bodymod, params=params)


if __name__ == '__main__':
    TestAddress = "http://fapi.xt-qa.com"
    symbol = 'test1658383498_usdt'

    xt = XT(
        url=TestAddress,
        access_key='b1000aa0-9119-4ce7-a963-e7a0fe0055cb',
        secret_key='b9992066608e6b84b531cbf1bf36b06e9a79add8'
        )

    # xt = XT(
    #     url=TestAddress,
    #     access_key='fd47e853-1997-435e-ae3f-a30524d24903',
    #     secret_key='c2e5a19e0d7f7aa6b9c5b7c2caa5a736024eaf50'
    #     )

    # order_list = [{"orderSide": "BUY",
    #                "orderType": "LIMIT",
    #                "origQty": 100+i,
    #                "positionSide": "LONG",
    #                "symbol": "btc_usdt",
    #                "price": 23000+i} for i in range(10)]
    # print(xt.send_batch_order(order_list=order_list))

    # print(xt.get_listen_key())
    print(xt.close_all_position())
    print(xt.cancel_all_order())
    # print(xt.set_account_leverage(leverage=1, position_side="SHORT", symbol=symbol))
    # print(xt.set_account_leverage(leverage=1, position_side="LONG", symbol=symbol))
    # print(xt.set_merge_position(symbol=symbol))   # 这是干啥的？
    # price*amount*0.01=quantity
    # print(xt.send_order(symbol=symbol, price=23100, amount=20, order_side="SELL", order_type="LIMIT", position_side="SHORT"))
    # print(xt.send_order(symbol=symbol, price=22800, amount=10, order_side="BUY", order_type="LIMIT", position_side="LONG"))
    # print(xt.get_batch_order_id(order_id_list=["83658649038409920", "83658649361371328"]))
    # print(xt.cancel_order(order_id='84103391789622144'))
    # print(xt.get_market_config(symbol=symbol))
    # print(xt.get_all_pair_info())
    # position = xt.get_position(symbol=symbol)
    # print(xt.get_funding_rate(symbol))
    # print(xt.get_agg_tiker(symbol))
    # print(xt.get_last_price(symbol, 10))
    # print(xt.get_depth(symbol, 10))
    # print(xt.get_account_capital())
    # print(xt.get_history_order())
    # res = xt.get_account_order(symbol=symbol, state="NEW", page=1, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # res = xt.get_account_order(symbol=symbol, state="UNFINISHED", page=1, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # res = xt.get_account_order(symbol=symbol, state="NEW", page=2, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # res = xt.get_account_order(symbol=symbol, state="NEW", page=3, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # res = xt.get_account_order(symbol=symbol, state="NEW", page=4, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # res = xt.get_account_order(symbol=symbol, state="NEW", page=5, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # res = xt.get_account_order(symbol=symbol, state="NEW", page=6, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # res = xt.get_account_order(symbol=symbol, state="UNFINISHED", page=1, size=100)
    # print(type(res), res.get('result').keys(), len(res.get('result').get('items')))
    # print(xt.get_index_price(symbol=symbol, size=1))
    
    
    # ########################################################################################## #
    # 准生产环境吃单后，订单薄没有改变

    # 问题描述：返回账户资产接口403
    # url:'http://fapi.ifunv.com/future/user/v1/balance/list'
    # hearder:{'Content-type': 'application/x-www-form-urlencoded', 'xt-validate-appkey': '0a10789e-af1b-4f35-ab5d-cf4ba1577a79', 'xt-validate-timestamp': '1646808973823', 'xt-validate-signature': '3397ba5636420f7f3941eefa4c05842452d77253b04873220ab90c0078242e64', 'xt-validate-algorithms': 'HmacSHA256'}

    # 问题描述：批量获取订单状态接口200 没有数据
    # url:'http://fapi.ifunv.com/future/trade/v1/order/list-by-ids?ids=71676480133190912'
    # hearder:{'Content-type': 'application/x-www-form-urlencoded', 'xt-validate-appkey': '0a10789e-af1b-4f35-ab5d-cf4ba1577a79', 'xt-validate-timestamp': '1646809660543', 'xt-validate-signature': '1b59416942b05869e6ee1f14dea8381ae4668fca8ec434980c55e6fa276b467c', 'xt-validate-algorithms': 'HmacSHA256'}
    # params:'ids':'71676480133190912'

    # 问题描述：下单接口502错误
    # url:'http://fapi.ifunv.com/future/trade/v1/order/create'
    # hearder:{'xt-validate-appkey': '0a10789e-af1b-4f35-ab5d-cf4ba1577a79', 'xt-validate-timestamp': '1646819791215', 'xt-validate-signature': '0b56e60bdb52987bf80b53e170fcdcec23640e8c1d0a990fa526ecc481a4a114', 'xt-validate-algorithms': 'HmacSHA256'}
    # params:{'orderSide': 'BUY', 'orderType': 'LIMIT', 'origQty': 100, 'positionSide': 'LONG', 'symbol': 'btc_usdt', 'price': 40001}

    # 问题描述：获取净值接口返回200，内容空
    # url:''http://fapi.ifunv.com/future/market/v1/public/q/symbol-mark-price?symbol=btc_usdt&size=1''
    # hearder:{'Date': 'Fri, 11 Mar 2022 03:37:25 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive'}
    # params:{'symbol': 'btc_usdt', 'size': 1}
